package com.example.huangliting.experimentalarrangementsystem.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.huangliting.experimentalarrangementsystem.R;
import com.example.huangliting.experimentalarrangementsystem.util.HttpUtils;
import com.example.huangliting.experimentalarrangementsystem.util.MD5Utils;
import com.example.huangliting.experimentalarrangementsystem.util.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class ModifyPasswordActicvity extends AppCompatActivity {

    private String submitModifyrUrl = HttpUtils.headerUrl+"teacher/modifyPassword";
    private TextView oldPasswordTv,newPasswordTv,confirmPasswordTv;
    private Button submitBtn,backBtn;
    private Context mcontext;
    private SharedPreferences sp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mcontext = this;
        setContentView(R.layout.modify_password);
        initView();
    }

    private void initView() {
        oldPasswordTv = findViewById(R.id.old_password);
        newPasswordTv = findViewById(R.id.new_password);
        confirmPasswordTv = findViewById(R.id.confirm_password);
        sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);


        submitBtn = findViewById(R.id.submit_modify_password);
        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                String oldPassword = oldPasswordTv.getText().toString();
                String newPassword = newPasswordTv.getText().toString();
                String confirmPassword = confirmPasswordTv.getText().toString();
                if (oldPassword==null || oldPassword.equals("")){
                    Toast.makeText(mcontext, "未填写原始密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (newPassword==null || newPassword.equals("")){
                    Toast.makeText(mcontext, "未填写新密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (confirmPassword==null || confirmPassword.equals("")){
                    Toast.makeText(mcontext, "未填写确认密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(!newPassword.equals(confirmPassword)){
                    Toast.makeText(mcontext, "新密码和确认密码不一致", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(oldPassword.equals(newPassword)){
                    Toast.makeText(mcontext, "原始密码和新密码不能相同", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (sp.getBoolean("ischeck",false)){
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("userId",sp.getString("userId",""));
                    params.put("oldPassword",MD5Utils.md5Password(oldPassword));
                    params.put("newPassword",MD5Utils.md5Password(newPassword));
                    submitModifyData(params, "utf-8");
                }
            }
        });

        /*返回操作*/
        backBtn = findViewById(R.id.toolbar_left_btn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                finish();
            }
        });
    }


    Handler submitHandler = new Handler() {

        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            try {
                JSONObject jsonObj = new JSONObject((String) msg.obj);
                int isSuccess = jsonObj.getInt("isSuccess");
                if(isSuccess == 0){
                    Toast.makeText(mcontext, "修改成功，请用新密码重新登录", Toast.LENGTH_LONG).show();
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putBoolean("isLogin",false);
                    editor.putBoolean("auto_ischeck",false);
                    editor.commit();
                    Intent i = new Intent(mcontext, LoginActivity.class);
                    startActivity(i);
                    finish();
                }else if(isSuccess==1){
                    Toast.makeText(mcontext, "修改失败", Toast.LENGTH_LONG).show();
                }else if(isSuccess==2){
                    Toast.makeText(mcontext, "原始密码错误", Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    private void submitModifyData(final Map<String, String> params, final String encode) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(submitModifyrUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = submitHandler.obtainMessage();
                        msg.obj = text;
                        submitHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

}
